#include "mytools.h"
#include <QDebug>

BOOL EnableDebugPrivilege()
{
    qInfo()<<GetLastError();
    HANDLE hToken;
    BOOL fOk=FALSE;

    if(OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES,&hToken))
    {
//        qInfo()<<"open OpenProcessToken "<<GetLastError();
        TOKEN_PRIVILEGES tp;
        tp.PrivilegeCount=1;
        LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&tp.Privileges[0].Luid);
        tp.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;

        AdjustTokenPrivileges(hToken,FALSE,&tp,sizeof(tp),NULL,NULL);

        fOk=GetLastError();
        CloseHandle(hToken);
    }
    qInfo()<<fOk<<GetLastError();
    return fOk;
}

static HANDLE gameProcess;

MyTools::MyTools()
{
}

MyTools::~MyTools()
{
    if(gameProcess)
        CloseHandle(gameProcess);
}

bool MyTools::findGame(QString className, QString windowName)
{
    static bool init = true;
    if(init){
        init = false;
        EnableDebugPrivilege();
    }

    HWND windowHandler = FindWindowW(reinterpret_cast<LPCWSTR>(className.utf16()),
                                     reinterpret_cast<LPCWSTR>(windowName.utf16()));

    qInfo()<<__FUNCTION__<<windowHandler;

    DWORD lpdwProcessId;
    GetWindowThreadProcessId(windowHandler, &lpdwProcessId);

    gameProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, lpdwProcessId);

    int error = GetLastError();
    qInfo()<<__FUNCTION__<<"gameProcess "<<gameProcess<<lpdwProcessId<<error;

    bool result = false;
    if(0 == error) result = true;
    return result;
}

void MyTools::updateValue(QString value)
{
    DWORD address = 0x00A1E0C4;   //静态基址+偏移量  (LPVOID)(*(LPVOID)address+offset)
    DWORD offset = 0x24C;
    int data = 0;
    int midAddress = 0;
    DWORD lpNumberOfBytesWritten = 0;

//    qInfo()<<"address "<<address<<offset<<address+offset;

    ReadProcessMemory(gameProcess, (LPVOID)(address), &midAddress, sizeof(midAddress), &lpNumberOfBytesWritten);
//    qInfo()<<"read1= "<<midAddress<<midAddress+offset<<GetLastError();

    ReadProcessMemory(gameProcess, (LPVOID)(midAddress+offset), &data, sizeof(data), &lpNumberOfBytesWritten);
    qInfo()<<"read2= "<<data<<GetLastError();

    data = value.toInt();
    int ret = WriteProcessMemory(gameProcess, (LPVOID)(midAddress+offset), &data, sizeof(data), &lpNumberOfBytesWritten);

    qInfo()<<"write "<<ret<<data<<GetLastError();

}
